package main; 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.StringTokenizer;

import util.Coordinate;

import model.Dictionary;
import model.Letter;
import model.Player;
import model.ScrabbleGame;
import model.Tile;

public class Main {
	private static ScrabbleGame game;

	public static void main(String[] args) throws IOException {
		int nb = 2;
		// Bag bag = new Bag();
		game = new ScrabbleGame();
		try {

			InputStreamReader ipsr = new InputStreamReader(System.in);
			BufferedReader br = new BufferedReader(ipsr);
			String ligne;
			System.out.println("Hello, and best luck !");
			System.out.println("How many player are you ? (2-4)");
			while ((ligne = br.readLine()) != null) {
				try {
					nb = Integer.parseInt(ligne);
					if (nb > 4) {
						nb = 4;
						System.out.println("Only 4 gamers can play!!!");
					}
					if (nb <= 1) {
						nb = 2;
						System.out.println("You MUST BE 2 a least");
					}
					break;
				} catch (NumberFormatException e) {
					System.out.println("How many player are you ?");
					System.out.println("please key in a number and enter");
				}
			}
			int j = 0;
			while (j < nb) {
				System.out.println("Please  key in the name of the gamer : "
						+ (j + 1));
				if ((ligne = br.readLine()) != null) {
					game.addPlayer(new Player(ligne));
					j++;
				}
			}
			game.start();
			String hello = "Hello ";
			for (j = 0; j < game.getPlayers().size(); j++) {
				hello += game.getPlayers().get(j).getName() + ", ";
			}
			System.out.println(hello);
			System.out.println("lets start the GAME");

			while ((ligne = br.readLine()) != null && !game.isEnded()) {
				System.out.println(game.getIBoard());
				System.out.println(game.getCurrentPlayer() + "\n>>");

				Scanner sc = new Scanner(System.in);
				String commande = sc.nextLine();
				StringTokenizer st = new StringTokenizer(commande);
				String action = "";
				try {
					if (st.hasMoreTokens())
						action = st.nextToken();
					else
						throw new IllegalArgumentException("Invalid action");
					// Command move
					if (action.equals(new String("move"))) {

						String type = "";
						if (st.hasMoreTokens())
							type = st.nextToken();
						else
							throw new IllegalArgumentException("Invalid type");

						int row = 0;
						if (st.hasMoreTokens())
							row = Integer.parseInt(st.nextToken());
						else
							throw new IllegalArgumentException("Invalid row");

						int column = 0;
						if (st.hasMoreTokens())
							column = Integer.parseInt(st.nextToken());
						else
							throw new IllegalArgumentException("Invalid column");

						String word = "";
						if (st.hasMoreTokens())
							word = st.nextToken();
						else
							throw new IllegalArgumentException("Invalid word");

						play(row, column, type.charAt(0), word);
					}
					// Command help
					else if (action.equals(new String("help"))) {
						System.out.println("help");
					}
					// Command skip
					else if (action.equals(new String("skip"))) {
						// On fait rien
						game.nextPlayer();
					}
					// Command tb
					else if (action.equals(new String("tb"))) {
						System.out.println(game.getIBoard().toString());
					}
					// Command lookup
					else if (action.equals(new String("lookup"))) {
						String mot = "";
						if (st.hasMoreTokens())
							mot = st.nextToken();

						if (Dictionary.getInstance().contains(mot)) {
							System.out.println("Le mot '" + mot
									+ "' est dans le dictionnaire");
						} else {
							System.out.println("Le mot '" + mot
									+ "' n'est pas dans le dictionnaire");
						}
					}
					// Command exchange
					else if (action.equals(new String("exchange"))) {
						String lettres = "";
						if (st.hasMoreTokens())
							lettres = st.nextToken();

						ArrayList<Letter> lettresList = new ArrayList<Letter>();
						for (char c : lettres.toCharArray()) {
							lettresList.add(Letter.valueOf(String.valueOf(c)));
						}

						game.getCurrentPlayer().getRack().takeAll(lettresList);
						game.nextPlayer();
					}
					// Command quit
					else if (action.equals(new String("quit"))) {
						game.endGame();
					}
					// Command invalid
					else
						System.out.println("Invalid command");
				} catch (IllegalArgumentException e) {
					System.out.println("Argument Error : " + e.getMessage());
				} catch (NullPointerException e) {
					System.out.println("Pointer Error : " + e.getMessage());
				} catch (Exception e) {
					System.out.println("Error : " + e.getMessage());
				}

			}
			game.endGame();

			br.close();
		} catch (IOException e) {
			System.err.println(e.toString());
		}
	}

	public static void play(int ligne, int colonne, char direction, String mot) {
		ArrayList<Letter> lettres = new ArrayList<Letter>();
		for (char c : mot.toCharArray()) {
			lettres.add(Letter.valueOf(String.valueOf(c)));
		}

		ArrayList<Tile> tuiles = game.getCurrentPlayer().getRack().takeAll(
				lettres);
		HashMap<Coordinate, Tile> tuilesPlacees = new HashMap<Coordinate, Tile>();
		if (direction == 'c') {
			Coordinate currentCoordinate = new Coordinate(ligne, colonne);
			for (Tile t : tuiles) {
				tuilesPlacees.put(currentCoordinate, t);
				currentCoordinate = currentCoordinate.south();
			}
		} else if (direction == 'r') {
			Coordinate currentCoordinate = new Coordinate(ligne, colonne);
			for (Tile t : tuiles) {
				tuilesPlacees.put(currentCoordinate, t);
				currentCoordinate = currentCoordinate.east();
			}
		} else {
			throw new IllegalArgumentException("Direction invalide");
		}
		try {
			game.play(tuilesPlacees);
			game.nextPlayer();
		} catch (Exception e) {
			game.getCurrentPlayer().getRack().refillAll(tuiles);
			System.out.println("Coup invalide : " + e.getMessage());
		}
	}
}
